package com.iplatform.iplatformuser.framework.privilege.dialect;

import com.iplatform.iplatformuser.framework.privilege.bean.GroupResourceBean;
import com.github.pagehelper.util.StringUtil;

/**
 * Title: OracleBoundsDialect
 * Description: oracle10.0.2版本以上资源过滤
 * @author RayLLi
 * @date 2019年6月29日
 */
public class OracleBoundsDialect extends AbstractDialect {

	/** 专业类型标志 */
	private final String specType = "SPEC";

	/** 行过滤类型 树形过滤 */
	private final String filterTreeType="treedown";

	/** 行过滤类型 in类型过滤 */
	private final String filterIndataType="indata";

	/**
	 * 数据权限专业和组织机构过滤
	 */
	@Override
	public String getResourceSql(String boundSql, GroupResourceBean groupResource) {
		if(StringUtil.isEmpty(groupResource.getResType())|| StringUtil.isEmpty(groupResource.getResFilterType())) {
			return boundSql;
		}

		//添加资源过滤
		StringBuilder sqlBuilder = new StringBuilder(boundSql.length() + 120);
		sqlBuilder.append("     SELECT   TMP_DATA.* 																													");
		sqlBuilder.append("       FROM   (  ").append(boundSql).append(" ) TMP_DATA																");

		sqlBuilder.append("  			  , (    SELECT   res_id 																											");
		sqlBuilder.append(" 		                FROM   STBL_RESOURCE sr 																						");
		sqlBuilder.append(" 		               WHERE   SR.RES_TYPE = '") .append(groupResource.getResType()) .append("' 		");

		//如果资源过滤的专业，则获取有效时间内的专业
		if(groupResource.getResType().equals(specType)) {
			sqlBuilder.append("  					AND SR.BEGIN_DATE < SYSDATE																			");
			sqlBuilder.append(" 					AND SR.END_DATE > SYSDATE																				");
		}

		//资源树形结构过滤
		if(groupResource.getResFilterType().equals(filterTreeType)) {
			sqlBuilder.append(" 		          START WITH    SR.RES_ID = '").append(groupResource.getResId()).append("' 			");
			sqlBuilder.append(" 		                    AND   SR.RES_TYPE = '") .append(groupResource.getResType()) .append("'	");
			sqlBuilder.append(" 		          CONNECT BY   SR.PARENT_ID = PRIOR SR.RES_ID) TMP_RES 									");
		}

		//指定资源过滤
		if(groupResource.getResFilterType().equals(filterIndataType)) {
			sqlBuilder.append(" AND SR.RES_ID IN (").append(groupResource.getResIds()).append(") ) TMP_RES						");
		}

		sqlBuilder.append(" 		 WHERE   TMP_DATA.").append(groupResource.getKeyId()).append(" = TMP_RES.RES_ID 	");

		return sqlBuilder.toString();
	}

	@Override
	public boolean skip(String boundSql, GroupResourceBean groupResourceBean) {
		return false;
	}

}
